package com.yami.shop.distribution.common.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.PhoneUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.Arith;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.common.util.PrincipalUtil;
import com.yami.shop.distribution.common.constants.DistributionUserIncomeStateEnum;
import com.yami.shop.distribution.common.constants.DistributionUserIncomeTypeEnum;
import com.yami.shop.distribution.common.dao.DistributionUserIncomeMapper;
import com.yami.shop.distribution.common.dao.DistributionUserWalletMapper;
import com.yami.shop.distribution.common.dto.DistributionOrderDto;
import com.yami.shop.distribution.common.dto.DistributionUserIncomeDto;
import com.yami.shop.distribution.common.dto.StatisticsDisUserIncomeDto;
import com.yami.shop.distribution.common.model.DistributionUserIncome;
import com.yami.shop.distribution.common.model.DistributionUserWallet;
import com.yami.shop.distribution.common.model.DistributionUserWalletBill;
import com.yami.shop.distribution.common.param.RangeTimeParam;
import com.yami.shop.distribution.common.service.DistributionUserIncomeService;
import com.yami.shop.distribution.common.service.DistributionUserWalletBillService;
import com.yami.shop.distribution.common.vo.DistributionOrdersVO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author lgh on 2019/04/01.
 */
@Service
@RequiredArgsConstructor
public class DistributionUserIncomeServiceImpl extends ServiceImpl<DistributionUserIncomeMapper, DistributionUserIncome> implements DistributionUserIncomeService {
    @Value("${yami.expose.operation.auth:}")
    private Boolean permission;

    private final DistributionUserIncomeMapper distributionUserIncomeMapper;

    private final DistributionUserWalletMapper distributionUserWalletMapper;

    private final DistributionUserWalletBillService distributionUserWalletBillService;


    @Override
    public IPage<DistributionUserIncome> incomeAndDistributionUserPage(Page page, Long shopId, RangeTimeParam rangeTimeParam, String userMobile, String orderNumber, Integer state,DistributionUserIncome distributionUserIncome) {
        IPage<DistributionUserIncome> userPage = distributionUserIncomeMapper.incomeAndDistributionUserPage(page, shopId, rangeTimeParam, userMobile, orderNumber, state, distributionUserIncome);
        if (BooleanUtil.isFalse(permission)) {
            for (DistributionUserIncome record : userPage.getRecords()) {
                record.getDistributionUser().setUserMobile(PhoneUtil.hideBetween(record.getDistributionUser().getUserMobile()).toString());
                if (PrincipalUtil.isMobile(record.getDistributionUser().getNickName())) {
                    record.getDistributionUser().setNickName(PhoneUtil.hideBetween(record.getDistributionUser().getNickName()).toString());
                }
            }
        }
        return userPage;
    }

    @Override
    public IPage<DistributionOrderDto> getDistributionOrderDtoByDistributionUserId(Page page, Long distributionUserId) {
        return distributionUserIncomeMapper.getDistributionOrderDtoByDistributionUserId(page, distributionUserId);
    }

    @Override
    public StatisticsDisUserIncomeDto statisticsDistributionUserIncome(Long distributionUserId) {
        StatisticsDisUserIncomeDto statisticsDisUserIncomeDto = new StatisticsDisUserIncomeDto();
        Date now = new Date();
        double todayAmount = distributionUserIncomeMapper.statisticsDisUserIncome(distributionUserId, DateUtil.beginOfDay(now), DateUtil.endOfDay(now));
        double monthAmount = distributionUserIncomeMapper.statisticsDisUserIncome(distributionUserId, DateUtil.beginOfMonth(now), DateUtil.endOfMonth(now));
        statisticsDisUserIncomeDto.setTodayAmount(todayAmount);
        statisticsDisUserIncomeDto.setMonthAmount(monthAmount);
        return statisticsDisUserIncomeDto;
    }

    @Override
    public IPage<DistributionUserIncomeDto> getDistributionUserIncomePage(PageParam<DistributionUserIncome> page, Long distributionUserId) {
        return distributionUserIncomeMapper.getDistributionUserIncomePage(page, distributionUserId);
    }

    @Override
    public IPage<DistributionOrdersVO> getMyPromotionOrderByState(PageParam<DistributionOrdersVO> page, Long distributionUserId, Integer state) {
        IPage<DistributionOrdersVO> promotionOrderPage = distributionUserIncomeMapper.getMyPromotionOrderByState(page, distributionUserId, state);
        promotionOrderPage.getRecords().forEach(distributionOrdersVO -> distributionOrdersVO.setCommissionRate(Arith.div(distributionOrdersVO.getDistributionAmount(), distributionOrdersVO.getPrice(), 4)));
        return promotionOrderPage;
    }

//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public void commissionSettlementHandle1(Date date) {
//        // 查询需要处理的支付收入记录,15天前确认收货的订单
//        List<DistributionUserIncome> distributionUserIncomeList = distributionUserIncomeMapper.listWaitCommissionSettlement(date);
//        List<DistributionUserIncome> updateBatchDistributionUserIncomeList = new ArrayList<>();
//        List<DistributionUserWalletBill> saveBatchDistributionWalletBillList = new ArrayList<>();
//
//        for (DistributionUserIncome distributionUserIncome : distributionUserIncomeList) {
//            // 减少用户的待结算佣金，添加已结算金额
//            DistributionUserWallet distributionUserWallet = distributionUserWalletMapper.selectById(distributionUserIncome.getWalletId());
//            if (distributionUserWallet == null) {
//                // 未找到分销员信息
//                throw new YamiShopBindException("yami.distribution.exist.error");
//            }
//
//            // 添加分销钱包日志
//            distributionUserWallet.setSettledAmount(Arith.add(distributionUserWallet.getSettledAmount(), distributionUserIncome.getIncomeAmount()));
//            distributionUserWallet.setUnsettledAmount(Arith.sub(distributionUserWallet.getUnsettledAmount(), distributionUserIncome.getIncomeAmount()));
//            distributionUserWallet.setAddupAmount(Arith.add(distributionUserWallet.getAddupAmount(), distributionUserIncome.getIncomeAmount()));
//            distributionUserWalletMapper.updateById(distributionUserWallet);
//
//            // 更新收入状态
//            updateBatchDistributionUserIncomeList.add(distributionUserIncome);
//
//            // 添加钱包变动日志
//            if (Objects.equals(DistributionUserIncomeTypeEnum.AWARD_ONE.getValue(), distributionUserIncome.getIncomeType())) {
//                saveBatchDistributionWalletBillList.add(new DistributionUserWalletBill(distributionUserWallet, "直推奖励","Direct push reward", -distributionUserIncome.getIncomeAmount(), distributionUserIncome.getIncomeAmount(), 0.0, distributionUserIncome.getIncomeAmount(), 0));
//            } else if (Objects.equals(DistributionUserIncomeTypeEnum.AWARD_TWO.getValue(), distributionUserIncome.getIncomeType())) {
//                saveBatchDistributionWalletBillList.add(new DistributionUserWalletBill(distributionUserWallet, "间推奖励","Indirect reward", -distributionUserIncome.getIncomeAmount(), distributionUserIncome.getIncomeAmount(), 0.0, distributionUserIncome.getIncomeAmount(), 0));
//            } else {
//                saveBatchDistributionWalletBillList.add(new DistributionUserWalletBill(distributionUserWallet, "邀请奖励","Invitation reward", -distributionUserIncome.getIncomeAmount(), distributionUserIncome.getIncomeAmount(), 0.0, distributionUserIncome.getIncomeAmount(), 0));
//            }
//        }
//        // 批量更新分销收入状态
//        if (CollectionUtils.isNotEmpty(updateBatchDistributionUserIncomeList)) {
//            if (distributionUserIncomeMapper.updateBatchState(updateBatchDistributionUserIncomeList, DistributionUserIncomeStateEnum.COMMISSION.getValue()) <= 0) {
//                // 批量更新分销收入状态失败
//                throw new YamiShopBindException("yami.distribution.batch.update.income");
//            }
//        }
//
//        // 批量添加钱包变动日志
//        if (CollectionUtils.isNotEmpty(saveBatchDistributionWalletBillList)) {
//            distributionUserWalletBillService.saveBatch(saveBatchDistributionWalletBillList);
//        }
//    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void commissionSettlementHandle(List<String> orderNumbers) {
        // 查询需要处理的支付收入记录,15天前确认收货的订单
        List<DistributionUserIncome> distributionUserIncomeList = distributionUserIncomeMapper.listWaitCommissionSettlement(orderNumbers);
        List<DistributionUserIncome> updateBatchDistributionUserIncomeList = new ArrayList<>();
        List<DistributionUserWalletBill> saveBatchDistributionWalletBillList = new ArrayList<>();

        for (DistributionUserIncome distributionUserIncome : distributionUserIncomeList) {
            // 减少用户的待结算佣金，添加已结算金额
            DistributionUserWallet distributionUserWallet = distributionUserWalletMapper.selectById(distributionUserIncome.getWalletId());
            if (distributionUserWallet == null) {
                // 未找到分销员信息
                throw new YamiShopBindException("yami.distribution.exist.error");
            }

            // 添加分销钱包日志
            distributionUserWallet.setSettledAmount(Arith.add(distributionUserWallet.getSettledAmount(), distributionUserIncome.getIncomeAmount()));
            distributionUserWallet.setUnsettledAmount(Arith.sub(distributionUserWallet.getUnsettledAmount(), distributionUserIncome.getIncomeAmount()));
            distributionUserWallet.setAddupAmount(Arith.add(distributionUserWallet.getAddupAmount(), distributionUserIncome.getIncomeAmount()));
            distributionUserWalletMapper.updateById(distributionUserWallet);

            // 更新收入状态
            updateBatchDistributionUserIncomeList.add(distributionUserIncome);

            // 添加钱包变动日志
            if (Objects.equals(DistributionUserIncomeTypeEnum.AWARD_ONE.getValue(), distributionUserIncome.getIncomeType())) {
                saveBatchDistributionWalletBillList.add(new DistributionUserWalletBill(distributionUserWallet, "直推奖励","Direct push reward", -distributionUserIncome.getIncomeAmount(), distributionUserIncome.getIncomeAmount(), 0.0, distributionUserIncome.getIncomeAmount(), 0));
            } else if (Objects.equals(DistributionUserIncomeTypeEnum.AWARD_TWO.getValue(), distributionUserIncome.getIncomeType())) {
                saveBatchDistributionWalletBillList.add(new DistributionUserWalletBill(distributionUserWallet, "间推奖励","Indirect reward", -distributionUserIncome.getIncomeAmount(), distributionUserIncome.getIncomeAmount(), 0.0, distributionUserIncome.getIncomeAmount(), 0));
            } else {
                saveBatchDistributionWalletBillList.add(new DistributionUserWalletBill(distributionUserWallet, "邀请奖励","Invitation reward", -distributionUserIncome.getIncomeAmount(), distributionUserIncome.getIncomeAmount(), 0.0, distributionUserIncome.getIncomeAmount(), 0));
            }
        }
        // 批量更新分销收入状态
        if (CollectionUtils.isNotEmpty(updateBatchDistributionUserIncomeList)) {
//            if (distributionUserIncomeMapper.updateBatchState(updateBatchDistributionUserIncomeList, DistributionUserIncomeStateEnum.COMMISSION.getValue(), DistributionAudit.INCOME_ZERO.getValue()) <= 0) {
//                // 批量更新分销收入状态失败
//                throw new YamiShopBindException("yami.distribution.batch.update.income");
////            }
            updateBatchDistributionUserIncomeList.forEach( item -> {
                item.setState(DistributionUserIncomeStateEnum.COMMISSION.getValue());
            });
            if (updateBatchState(updateBatchDistributionUserIncomeList) <= 0){
                throw new YamiShopBindException("yami.distribution.batch.update.income");
            }
        }

        // 批量添加钱包变动日志
        if (CollectionUtils.isNotEmpty(saveBatchDistributionWalletBillList)) {
            distributionUserWalletBillService.saveBatch(saveBatchDistributionWalletBillList);
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int updateBatchState(List<DistributionUserIncome> distributionUserIncomeList){
        int i = 0;
        for (DistributionUserIncome entity :
                distributionUserIncomeList) {
            int b = distributionUserIncomeMapper.updateById(entity);
            if (b > 0){
                i++;
            }
        }
        return i;
    }

}
